﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HostTool.Core;
using HostTool.Protocol;
using System.IO;
using System.Threading;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win.UltraWinEditors;
using GF;

namespace HostTool.GUI
{
    public partial class FormCPU : Form
    {

        const int UpateResetTime = 30;

        CPU cpu;
        Thread threadUpload;


        bool showInner = false;


        int[] showVerInner = new int[] { 0x10, 0x10, 0x10 }; //0x10-显示外部版本号 0x28-显示内部版本号

        public FormCPU()
        {
            InitializeComponent();
        }

        public FormCPU(CPU cpu)
            : this()
        {
            this.cpu = cpu;
            this.cpu.ChannelDataUpdate += new EventHandler(Cpu_ChannelDataUpdate);

            showInner = File.Exists(Path.Combine(Application.StartupPath, "Version.txt"));

        

           

            if (cpu is CPURecord)
            {
                groupBox5.Visible = true;
                if (showInner)
                {
                    showVerInner = new int[] { 0x10, 0x28, 0x28 };
                   
                }
                else
                {
                    groupBox5.Visible = false;
                    showVerInner = new int[] { 0x10, 0x10, 0x10 };
                }
            }
            else if (cpu is CPUSample)
            {
                groupBox5.Visible = false;
                if (showInner)
                {
                    showVerInner = new int[] { 0x10, 0x28, 0x28 };
                }
                else
                {
                    showVerInner = new int[] { 0x10, 0x10, 0x10 };
                    
                }
            }
            else
            {
                groupBox5.Visible = false;
                showVerInner = new int[] { 0x10, 0x10, 0x10 };
            }

        }

       

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);


            InitBasicInfo();
            InitFirmwareList();
            InitChannelGrid();

           
        }


        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            btnReadParam_Click(null, null);
        }

        void InitBasicInfo()
        {
            btUpload.Enabled = false;
            label5.Text = cpu.Descriptor;
        }

        void InitFirmwareList()
        {
            IList<FirmwareType> list = cpu.FirmwareList;
            RadioButton firstButton = null;
            for (int i = 0; i < list.Count; i++)
            {
                FirmwareType firmware = list[i];
                RadioButton rButton = new RadioButton();
                rButton.Name = "radiao_button" + i;
                rButton.Font = new Font("宋体", 14);
                rButton.Text = firmware.Name;
                rButton.Tag = firmware;
                rButton.AutoSize = true;
                int row = i / 4;
                int col = i % 4;
                rButton.Location = new Point(col * 160 + 20, 15+row*50);
                groupBox3.Controls.Add(rButton);
                if (firstButton == null)
                {
                    firstButton = rButton;
                }

            }
            if (firstButton != null)
            {
                firstButton.Checked = true;
            }
        }
        void InitChannelGrid()
        {
            ultraGrid1.DisplayLayout.GroupByBox.Hidden = true;
            //选择的
            ultraGrid1.DisplayLayout.Override.RowSelectors = Infragistics.Win.DefaultableBoolean.True;
            ultraGrid1.DisplayLayout.Override.RowSelectorHeaderStyle = RowSelectorHeaderStyle.ColumnChooserButton;
            ultraGrid1.DisplayLayout.Override.AllowColMoving = AllowColMoving.NotAllowed;
            ultraGrid1.DisplayLayout.Override.HeaderClickAction = HeaderClickAction.Select;
            //设置行高
            ultraGrid1.DisplayLayout.Override.DefaultRowHeight = 25;

            ultraGrid1.DisplayLayout.Bands[0].Columns.Add("Select", "选择");
            ultraGrid1.DisplayLayout.Bands[0].Columns.Add("Name", "通道名称").CellClickAction = CellClickAction.CellSelect;
            ultraGrid1.DisplayLayout.Bands[0].Columns.Add("VoltageOffset", "直流偏置").CellClickAction = CellClickAction.CellSelect;
            ultraGrid1.DisplayLayout.Bands[0].Columns.Add("VoltageSample", "采集电压").CellClickAction = CellClickAction.CellSelect;
            ultraGrid1.DisplayLayout.Bands[0].Columns.Add("VoltageReal", "实际电压").Nullable = Infragistics.Win.UltraWinGrid.Nullable.EmptyString;

            ultraGrid1.DisplayLayout.Bands[0].Columns.Add("OffsetParam", "偏置参数").Nullable = Infragistics.Win.UltraWinGrid.Nullable.EmptyString;
            ultraGrid1.DisplayLayout.Bands[0].Columns.Add("CoeffParam", "系数参数").Nullable = Infragistics.Win.UltraWinGrid.Nullable.EmptyString;
         

            

            foreach (UltraGridColumn ultraCol in ultraGrid1.DisplayLayout.Bands[0].Columns)
            {
                ultraCol.Header.Appearance.TextHAlign = Infragistics.Win.HAlign.Center;
                ultraCol.Header.Appearance.TextVAlign = Infragistics.Win.VAlign.Middle;
                ultraCol.Width = 200;
                
            }
            ultraGrid1.DisplayLayout.Bands[0].Columns["Select"].Width = 50;
            ultraGrid1.DataSource = cpu.Channels;

            
        }


        void Cpu_ChannelDataUpdate(object sender, EventArgs e)
        {
            this.Invoke(new MethodInvoker(delegate {

                ultraGrid1.Refresh();
            }));
        }

        private void buttonVersion_Click(object sender, EventArgs e)
        {

            tbBiosVersion.Clear();
            tbBiosDate.Clear();
            tbAppVersion.Clear();
            tbAppDate.Clear();

           RequestPackage package= cpu.CreateRequest(0x03, 0x09,1000);
       
           package.CallbackHandler = new RequestCallbackHandler(ProcessVersion);
           cpu.SendRequest(package);

           RequestPackage packageInner = cpu.CreateRequest(0x03, 0x27, 2000); //发送0x27返回0x28 //内部版本号
           packageInner.CallbackHandler = new RequestCallbackHandler(ProcessVersion);
           cpu.SendRequest(packageInner);

        }

        private void ProcessVersion(Frame frame)
        {
            if (frame != null)
            {
                int cmd = frame.Cmd;
                this.Invoke(new MethodInvoker(delegate
                {

                    int N = frame.RealDataLength / 7;
                    byte[] data = frame.RawData;
                    int offset = frame.RealDataOffset;
                    for (int i = 0; i < N; i++)
                    {
                        //版本
                        StringBuilder sbVer = new StringBuilder("V");
                        string vers=  data[offset + i * 7 + 1].ToString("X2");

                        sbVer.Append(vers[0] + "." + vers[1]+".");
                        vers = data[offset + i * 7 + 2].ToString("X2");
                        sbVer.Append(vers[0] + "." + vers[1]);
                        StringBuilder sbTime = new StringBuilder();

                        sbTime.Append(data[offset + i * 7 + 3].ToString("X2"));
                        sbTime.Append(data[offset + i * 7 + 4].ToString("X2"));
                        sbTime.Append("年");


                        sbTime.Append(data[offset + i * 7 + 5].ToString("X2"));
                        sbTime.Append("月");
                        sbTime.Append(data[offset + i * 7 + 6].ToString("X2"));
                        sbTime.Append("日");
                        switch (data[offset + i * 7])
                        {
                            case 0:
                                if (showVerInner[0] == cmd)
                                {
                                    tbBiosVersion.Text = sbVer.ToString();
                                    tbBiosDate.Text = sbTime.ToString();
                                }
                                break;
                            case 1:
                                if (showVerInner[1] == cmd)
                                {
                                    tbAppVersion.Text = sbVer.ToString();
                                    tbAppDate.Text = sbTime.ToString();
                                }
                                break;
                            case 2:
                                if (showVerInner[2] == cmd)
                                {
                                    textBoxUSBVer.Text = sbVer.ToString();
                                    textBoxUSBDate.Text = sbTime.ToString();
                                }
                                break;
                        }


                    }

                }));
            }
        }

        private void btOpenFile_Click(object sender, EventArgs e)
        {
            foreach (Control ctrl in groupBox3.Controls)
            {
                RadioButton rb = ctrl as RadioButton;
                if (rb != null && rb.Checked)
                {
                    FirmwareType type = rb.Tag as FirmwareType;

                    firmwareType = type;
                }
            }
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "Hex文件|*.hex|BIN文件|*.bin|参数文件|*.txt";
                ofd.InitialDirectory = LrnS.GetItem("firmwareAddress" + firmwareType.Name);
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    LrnS.SaveItem("firmwareAddress" + firmwareType.Name, Path.GetDirectoryName(ofd.FileName));
                    tbFileLocation.Text = ofd.FileName;
                    btUpload.Enabled = true;
                }
            }
        }





        FirmwareType firmwareType = null;

        private void btUpload_Click(object sender, EventArgs e)
        {

            threadUpload = new Thread(new ParameterizedThreadStart(ProcUpdateFirmware));
            threadUpload.IsBackground = true;
            threadUpload.Start(tbFileLocation.Text);

          
            foreach(Control ctrl in groupBox3.Controls)
            {
                RadioButton rb = ctrl as RadioButton;
                if (rb != null && rb.Checked)
                {
                    FirmwareType type = rb.Tag as FirmwareType;

                    firmwareType = type;
                }
            }

            btUpload.Enabled = false;
        }

        /// <summary>
        /// 更新固件文件
        /// </summary>
        private void ProcUpdateFirmware(object args)
        {

            string fileName = (string)args;


            this.Invoke(new MethodInvoker(delegate
            {
                lbUpdateStatus.ForeColor = Color.Black;
                lbUpdateStatus.Text = "准备升级";
                pbUpdate.Value = 0;
            }));

            //文件不存在
            if (File.Exists(fileName) == false)
            {
                this.Invoke(new MethodInvoker(delegate {
                    lbUpdateStatus.Text = "升级失败:文件不存在!";
                    lbUpdateStatus.ForeColor = Color.Red;
                    btUpload.Enabled = true;

                }));

                return;
            }


            byte[] fileData = File.ReadAllBytes(fileName);

            fileData = firmwareType.Convert(fileData);

            //计算传输的帧个数
            int frameCnt = fileData.Length / cpu.MTU;
            int leftLength = fileData.Length % cpu.MTU;

            if (leftLength > 0)
            {
                frameCnt++;
            }
            //计算开始升级帧数据
            byte[] frameTx=new byte[4];
            int maxFrameNum=frameCnt-1;

            frameTx[0] = 1; //0-软件升级 1-文件下载 SIL4Version
            if(firmwareType.Type == 0x73)
                frameTx[0] = 2; //0-软件升级 1-文件下载 SIL4Version

            frameTx[1] = (byte)(maxFrameNum >> 8);
            frameTx[2]=(byte)(maxFrameNum&0xff);
            frameTx[3] = firmwareType.Type; //软件类型

            byte[] frameData = new byte[2 + cpu.MTU];

            bool resetOK = false;


            RequestPackage package = cpu.CreateRequest(0x02, 0x08, 100);
            for (int i = 0; i < 3; i++)
            {
                //(1)复位
                

                cpu.SendRequest(package);

                Frame frame = package.WaitResponse();

                if (frame != null)
                {
                    
                }

                for (int j = 0; j < 4; j++)
                {
                    Thread.Sleep(1000);

                    this.Invoke(new MethodInvoker(delegate
                    {
                        lbUpdateStatus.ForeColor = Color.Black;
                        lbUpdateStatus.Text = String.Format("等待CPU重启({0})秒...", 4 - j);
                    }));

                }

                //(2)发送升级命令
                this.Invoke(new MethodInvoker(delegate
                {
                    lbUpdateStatus.Text = "发送升级命令";
                }));
                package = cpu.CreateRequest(0x03, 0x11, frameTx,frameTx.Length,10000);
                cpu.SendRequest(package);
                frame = package.WaitResponse(); //等待10秒
                if (frame != null)
                {
                    int dOffset=frame.RealDataOffset;
                    if (frame.RawData[dOffset] == 0x11)
                    {
                        resetOK = true;
                        break;
                    }
                }
            }

            if (resetOK == false)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    lbUpdateStatus.Text = "升级失败:CPU复位失败!";
                    lbUpdateStatus.ForeColor = Color.Red;
                    btUpload.Enabled = true;
                }));
                return;
            }
            //(3)发送固件数据
            int offset = 0;
            for (int i = 0; i < frameCnt; i++)
            {

                this.Invoke(new MethodInvoker(delegate
                {
                    lbUpdateStatus.Text = String.Format("发送升级包({0}/{1})", i + 1, frameCnt);
                }));

                int txLen = cpu.MTU;
                if ((i == frameCnt - 1) && (leftLength > 0))
                {
                    txLen = leftLength;
                }
                Array.Copy(fileData, offset, frameData, 2, txLen);
                offset +=txLen;
                
                frameData[0]=(byte)(i>>8); //帧序号
                frameData[1] = (byte)(i & 0xff);

                 package = cpu.CreateRequest(0x03, 0x12, frameData, txLen+2,5000);
          
                bool sendOK = false;
                for (int j = 0; j < 3; j++)
                {
                  
                    cpu.SendRequest(package);

                    Frame frame = package.WaitResponse();
                    if (frame != null)
                    {
                        int dOffset = frame.RealDataOffset;
                        if (frame.Cmd == 0x82)
                        {
                            if (frame.RawData[dOffset] != frameData[0]) continue;
                            if (frame.RawData[dOffset + 1] != frameData[1]) continue;
                            if (frame.RawData[dOffset + 2] != 0) continue;
                        }
                        else if (frame.Cmd == 0x01)
                        {
                            if (frame.RawData[dOffset + 1] != 0) continue;
                        }
                        else
                            continue;

                        sendOK = true;

                        this.Invoke(new MethodInvoker(delegate
                        {
                            pbUpdate.Value = pbUpdate.Maximum * (i + 1) / frameCnt;
                        }));
                        break;
                    }
                }

                if (sendOK == false)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        lbUpdateStatus.Text = "升级失败:发送升级数据包失败!";
                        lbUpdateStatus.ForeColor = Color.Red;
                        btUpload.Enabled = true;
                    }));
                    return;
                }


            }

            //(4)等待应用程序启动
            bool updateResetOK = false;
            package = cpu.CreateRequest(0x03, 0x14, 2000);
            for (int i = 0; i < UpateResetTime; i++)
            {
                

                cpu.SendRequest(package);

                this.Invoke(new MethodInvoker(delegate
                {
                    lbUpdateStatus.Text = String.Format("查询升级状态({0}/{1})...", i + 1, UpateResetTime);
             
                }));

                Frame frame = package.WaitResponse();

                if (frame != null)
                {
                   
                    if (frame.RawData[frame.RealDataOffset] == 0)
                    {
                        updateResetOK = true;

                        this.Invoke(new MethodInvoker(delegate
                        {
                            lbUpdateStatus.Text = "升级成功!";
                            lbUpdateStatus.ForeColor = Color.Green;
                            //MessageBox.Show("升级成功");
                            btUpload.Enabled = true;
                        }));
                        break;
                    }
                }
                Thread.Sleep(1000);

            }
            if (updateResetOK == false)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    lbUpdateStatus.Text = "升级失败:查询升级状态失败!";
                    lbUpdateStatus.ForeColor = Color.Red;
                    //MessageBox.Show("升级成功");
                    btUpload.Enabled = true;
                }));
            }

        }

        private void btTimeQuery_Click(object sender, EventArgs e)
        {
            txtCPUTime.Clear();
            RequestPackage package = cpu.CreateRequest(0x05, 0x22, 1000);
            package.CallbackHandler = new RequestCallbackHandler(ProcessCPUTime);
            cpu.SendRequest(package);

        }

        private void ProcessCPUTime(Frame frame)
        {
            this.Invoke(new MethodInvoker(delegate
            {
                if (frame != null)
                {
                    byte[] data = frame.RawData;
                    int offset = frame.RealDataOffset;
                    txtCPUTime.Text = string.Format("{0}年{1}月{2}日 {3}:{4}:{5}", data[offset]+2000, data[offset + 1].ToString("00"), data[offset + 2].ToString("00"),
                        data[offset + 3].ToString("00"), data[offset + 4].ToString("00"), data[offset + 5].ToString("00"));
                }
                else
                {
                    txtCPUTime.Text = "---";
                }

            }));
        }

        private void btSetTime_Click(object sender, EventArgs e)
        {
            lbSetTimeResult.Visible = false;
            DateTime time = dateTimePicker1.Value;
            byte[] data=new byte[6];
            data[0] = (byte)(time.Year - 2000);
            data[1] = (byte)time.Month;
            data[2] = (byte)time.Day;
            data[3] = (byte)time.Hour;
            data[4] = (byte)time.Minute;
            data[5] = (byte)time.Second;
            RequestPackage package = cpu.CreateRequest(0x05, 0x24, data, data.Length, 1000);
            package.CallbackHandler = new RequestCallbackHandler(ProcessSetTime);
            cpu.SendRequest(package);
        }

        private void ProcessSetTime(Frame frame)
        {
            if (frame != null)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    lbSetTimeResult.Text = "设置时间成功!";
                    lbSetTimeResult.ForeColor = Color.Green;
                    lbSetTimeResult.Visible = true;
                }));
            }
        }


        private void btSyncTime_Click(object sender, EventArgs e)
        {
            lbSetTimeResult.Visible = false;
            DateTime time = DateTime.Now;
            byte[] data = new byte[6];
            data[0] = (byte)(time.Year - 2000);
            data[1] = (byte)time.Month;
            data[2] = (byte)time.Day;
            data[3] = (byte)time.Hour;
            data[4] = (byte)time.Minute;
            data[5] = (byte)time.Second;
            RequestPackage package = cpu.CreateRequest(0x05, 0x24, data, data.Length, 1000);
            package.CallbackHandler = new RequestCallbackHandler(ProcessSetTime);
            cpu.SendRequest(package);
        }


        private void btnRefreshOffset_Click(object sender, EventArgs e)
        {
            cpu.QueryChannelOffsetEnabled = !cpu.QueryChannelOffsetEnabled;

            if (cpu.QueryChannelOffsetEnabled)
            {
                btnRefreshOffset.Appearance.Image = Properties.Resources.StopQuery;
            }
            else
            {
                btnRefreshOffset.Appearance.Image = Properties.Resources.StartQuery;
            }
        }

        private void btRefreshChannelData_Click(object sender, EventArgs e)
        {
            cpu.QueryChannelDataEnabled = !cpu.QueryChannelDataEnabled;
          
            if (cpu.QueryChannelDataEnabled)
            {
                btRefreshChannelData.Appearance.Image = Properties.Resources.StopQuery;
             
            }
            else
            {
                btRefreshChannelData.Appearance.Image = Properties.Resources.StartQuery;
            }
        }

  

        private void button4_Click(object sender, EventArgs e)
        {
            MessageBox.Show(cpu.Channels[0].CoeffParam);
        }

        private void btnReadParam_Click(object sender, EventArgs e)
        {
            if (cpu.Channels.Count == 0) return;
            RequestPackage package = cpu.CreateRequest(0x01, 0x03, 1000);

            package.CallbackHandler = new RequestCallbackHandler(ProcessParamRead);
            cpu.SendRequest(package);
        }

        private void ProcessParamRead(Frame frame)
        {
            if (frame != null)
            {
                this.Invoke(new MethodInvoker(delegate
                {

                    byte[] data = frame.RawData;
                    int offset = frame.RealDataOffset;
                    int cnt = frame.RealDataLength/4;
                    for (int i = 0; i < cnt; i++)
                    {
                        int offsetParam = data[offset + i * 4] + (data[offset + i * 4 + 1] << 8);
                        int coeffParam = data[offset + i * 4+2] + (data[offset + i * 4 + 3] << 8);

                        cpu.Channels[i].OffsetParam = offsetParam.ToString();
                        cpu.Channels[i].CoeffParam = coeffParam.ToString();

                    }

                    ultraGrid1.Refresh();
                    

                }));
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="startChannel">开始的通道</param>
        /// <param name="reCal">是否重新计算系数</param>
        /// <returns></returns>
        byte[] GetParamData(int startChannel,bool reCal)
        {
            int channelNum = cpu.Channels.Count;
            if (channelNum > 26) { channelNum = 26; }

            int extraNum = startChannel >= 0 ? 1 : 0;

            byte[] data = new byte[channelNum * 4+extraNum];
            if (extraNum > 0)
            {
                data[0] = (byte)startChannel;
            }
     
            for (int i = 0; i < channelNum; i++)
            {
                int offsetParam = 0;
                int.TryParse(cpu.Channels[i].OffsetParam, out offsetParam);


                data[i * 4+extraNum] = (byte)(offsetParam & 0xff);
                data[i * 4 + 1+extraNum] = (byte)(offsetParam >> 8);


                int coeffParam = 1;
                int.TryParse(cpu.Channels[i].CoeffParam, out coeffParam);

                if (cpu.Channels[i].Select && !string.IsNullOrEmpty(cpu.Channels[i].VoltageSample) && !string.IsNullOrEmpty(cpu.Channels[i].VoltageReal) && reCal)
                {


                    int volSample = 1;
                    int volReal = 1;
                    int.TryParse(cpu.Channels[i].VoltageSample, out volSample);
                    int.TryParse(cpu.Channels[i].VoltageReal, out volReal);

                    coeffParam = coeffParam * volReal / volSample;
                    cpu.Channels[i].CoeffParam = coeffParam.ToString();
                }


                data[i * 4 + 2+extraNum] = (byte)(coeffParam & 0xff);
                data[i * 4 + 3+extraNum] = (byte)(coeffParam >> 8);



            }

            ultraGrid1.Refresh();

            return data;
        }

        private void btnWriteParam_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确认写入参数？", "提醒", MessageBoxButtons.YesNo,MessageBoxIcon.Warning) == DialogResult.No) return;



            byte[] data = GetParamData(-1,false);

            RequestPackage package = cpu.CreateRequest(0x01, 0x02, data,data.Length, 1000);

            package.CallbackHandler = new RequestCallbackHandler(ProcessParamWrite);
            cpu.SendRequest(package);

        }


        private void ProcessParamWrite(Frame frame)
        {
            if (frame != null)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    MessageBox.Show("写入参数OK！","",MessageBoxButtons.OK,MessageBoxIcon.Information);


                }));
            }
        }

    

        private void btnConfigChannel_Click(object sender, EventArgs e)
        {
            byte[] data = GetParamData(0,true);

            RequestPackage package = cpu.CreateRequest(0x0a, 0xb8, data, data.Length, 1000);

            package.CallbackHandler = new RequestCallbackHandler(ProcessParamTmp);
            cpu.SendRequest(package);
        }

        private void ProcessParamTmp(Frame frame)
        {
            if (frame != null)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    


                }));
            }
        }


        byte GetSectorLockState()
        {
            byte state = 0;
            foreach (Control contrl in groupBox4.Controls)
            {
                UltraCheckEditor checkEditor = contrl as UltraCheckEditor;
                if (checkEditor != null && checkEditor.Tag != null && checkEditor.Checked)
                {
                    int bit = int.Parse(checkEditor.Tag.ToString());
                    state = (byte)(state | (1 << bit));
                }
            }

            return state;
        }

        private void btnLock_Click(object sender, EventArgs e)
        {
            byte state = GetSectorLockState();
            byte[] data = new byte[7];

            data[0] = 0xaa;
            data[1] = state;
            //特征码  0x76546231
            data[2] = 0x31;
            data[3] = 0x62;
            data[4] = 0x54;
            data[5] = 0x76;
            data[6] = data[0];
            RequestPackage package = cpu.CreateRequest(0x0a, 0xaa, data,data.Length, 1000);

            package.CallbackHandler = new RequestCallbackHandler(ProcessFlash);
            cpu.SendRequest(package);


        }

        private void btnUnlock_Click(object sender, EventArgs e)
        {
            byte state = GetSectorLockState();
            byte[] data = new byte[7];

            data[0] = 0x55;
            data[1] = state;
            //特征码  0x54763162解锁
            data[2] = 0x62;
            data[3] = 0x31;
            data[4] = 0x76;
            data[5] = 0x54;
            data[6] = data[0];
            RequestPackage package = cpu.CreateRequest(0x0a, 0xaa, data, data.Length, 1000);

            package.CallbackHandler = new RequestCallbackHandler(ProcessFlash);
            cpu.SendRequest(package);
        }


        private void ProcessFlash(Frame frame)
        {
            if (frame != null)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    byte status=frame.RawData[frame.RealDataOffset];
                    if (status == 0)
                    {
                        MessageBox.Show("操作成功!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("操作失败!,错误码:"+status, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                

                }));
            }
        }

        private void btnAutoFill_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < cpu.Channels.Count; i++)
            {
                cpu.Channels[i].OffsetParam = cpu.Channels[i].VoltageOffset;
            }

            this.ultraGrid1.Refresh();
        }

        private void btAllSel_Click(object sender, EventArgs e)
        {
            IList<CPUChannel> channels = cpu.Channels;

            if (channels != null)
            {
                foreach (CPUChannel channel in channels)
                {
                    channel.Select = true;
                }
            }

            ultraGrid1.Refresh();
        }

        private void btAllCancel_Click(object sender, EventArgs e)
        {
            IList<CPUChannel> channels = cpu.Channels;

            if (channels != null)
            {
                foreach (CPUChannel channel in channels)
                {
                    channel.Select = false;
                }
            }

            ultraGrid1.Refresh();
        }

        private void btVoltSame_Click(object sender, EventArgs e)
        {
            IList<CPUChannel> channels = cpu.Channels;

            if (channels != null)
            {
                for (int i = 1; i < channels.Count; i++)
                {
                    channels[i].VoltageReal = channels[0].VoltageReal;
                }
            }

            ultraGrid1.Refresh();
        }

        private void btOffsetSame_Click(object sender, EventArgs e)
        {
            IList<CPUChannel> channels = cpu.Channels;

            if (channels != null)
            {
                for (int i = 1; i < channels.Count; i++)
                {
                    channels[i].OffsetParam = channels[0].OffsetParam;
                }
            }

            ultraGrid1.Refresh();
        }

        private void btCoeffSame_Click(object sender, EventArgs e)
        {
            IList<CPUChannel> channels = cpu.Channels;

            if (channels != null)
            {
                for (int i = 1; i < channels.Count; i++)
                {
                    channels[i].CoeffParam = channels[0].CoeffParam;
                }
            }

            ultraGrid1.Refresh();
        }

      


    }
}
